/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pb138.srgsxmldb.servlets;

import cz.muni.fi.pb138.srgsxmldb.manager.IXManager;
import cz.muni.fi.pb138.srgsxmldb.manager.XManager;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * this class provides functionality of downloading specific xml srgs grammar file from database
 * 
 * @author Eldred
 */
public class DownloadServlet extends HttpServlet{
 
  private static final int BYTES_DOWNLOAD = 1024;
 
    @Override
    public void doGet(HttpServletRequest request, 
    HttpServletResponse response) throws IOException{
        
        String filename = (String) request.getParameter("file");
        
        if (filename != null) {
            
            IXManager manager = new XManager();
            File file = manager.getGrammarFileByFileName(filename);
            
            FileInputStream fileToDownload = new FileInputStream(file);

            response.setContentType("text/plain");
            response.setHeader("Content-Disposition", "attachment;filename="+file.getName()); 

            int read=0;
            byte[] bytes = new byte[BYTES_DOWNLOAD];
            OutputStream os = response.getOutputStream();


                while((read = fileToDownload.read(bytes))!= -1){
                        os.write(bytes, 0, read);
                }

            os.flush();
            os.close();
            fileToDownload.close();
        }
   }
}
